import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { supabase } from '../lib/supabase'
import type { User } from '../types/ui'
import type { User as SupabaseUser } from '@supabase/supabase-js'
import type { 
  UserRole, 
  RoleChangeLog, 
  SetUserRoleParams,
  BatchSetUserRolesParams,
  SetUserRoleResponse,
  BatchSetUserRolesResponse,
  UserWithRole,
  AdminStats
} from '../types/admin'

const base = import.meta.env.BASE_URL || '/'

export const useUserStore = defineStore('user', () => {
  // 认证状态
  const user = ref<SupabaseUser | null>(null)
  const loading = ref(true)
  
  // 用户资料信息
  const userProfile = ref<User | null>(null)
  const profileLoading = ref(false)
  
  // 用户角色和权限
  const currentUserRole = ref<UserRole>('user')
  const roleLoading = ref(false)
  
  // 管理员功能状态
  const adminLoading = ref(false)
  const adminError = ref<string | null>(null)

  // 认证状态订阅（可清理）
  let authSubscription: { unsubscribe?: () => void } | null = null
  
  // 认证模态框状态
  const showLoginModal = ref(false)
  const showRegisterModal = ref(false)

  // 认证方法
  const signUp = async (email: string, password: string) => {
    try {
      const { data, error } = await supabase.auth.signUp({
        email,
        password,
        options: {
          emailRedirectTo: `${base}/auth/callback`,
        },
      })
      if (error) throw error
      return { data, error: null }
    } catch (error) {
      console.error('Error signing up:', error)
      return { data: null, error }
    }
  }

  const signIn = async (email: string, password: string) => {
    try {
      const { data, error } = await supabase.auth.signInWithPassword({
        email,
        password,
      })
      if (error) throw error
      user.value = data.user
      // 登录成功后自动获取用户资料
      if (data.user) {
        await fetchUserProfile(data.user.id)
      }
      return { data, error: null }
    } catch (error) {
      console.error('Error signing in:', error)
      return { data: null, error }
    }
  }

  const signOut = async () => {
    try {
      const { error } = await supabase.auth.signOut()
      if (error) throw error
      user.value = null
      userProfile.value = null
      return { error: null }
    } catch (error) {
      console.error('Error signing out:', error)
      return { error }
    }
  }

  const signInWithGoogle = async () => {
    try {
      const { data, error } = await supabase.auth.signInWithOAuth({
        provider: 'google',
        options: {
          redirectTo: `${base}/auth/callback`,
        },
      })
      if (error) throw error
      return { data, error: null }
    } catch (error) {
      console.error('Error signing in with Google:', error)
      return { data: null, error }
    }
  }

  const resendConfirmationEmail = async (email: string) => {
    try {
      const { error } = await supabase.auth.resend({
        type: 'signup',
        email,
        options: {
          emailRedirectTo: `${base}/auth/callback`,
        },
      })
      if (error) throw error
      return { error: null }
    } catch (error) {
      console.error('Error resending confirmation email:', error)
      return { error }
    }
  }

  const resetPassword = async (email: string) => {
    try {
      const { error } = await supabase.auth.resetPasswordForEmail(email, {
        redirectTo: `${base}/auth/callback`,
      })
      if (error) throw error
      return { error: null }
    } catch (error) {
      console.error('Error resetting password:', error)
      return { error }
    }
  }

  // 检查用户角色
  const checkUserRole = async () => {
    if (!user.value) {
      currentUserRole.value = 'user'
      return 'user'
    }
    
    roleLoading.value = true
    try {
      const { data, error: roleError } = await supabase.rpc('get_user_role')

      if (roleError) {
        console.error('Error checking user role:', roleError)
        currentUserRole.value = 'user'
        return 'user'
      }

      currentUserRole.value = data as UserRole
      return data as UserRole
    } catch (err) {
      console.error('Error in checkUserRole:', err)
      currentUserRole.value = 'user'
      return 'user'
    } finally {
      roleLoading.value = false
    }
  }

  // 检查是否为管理员
  const isAdmin = async (): Promise<boolean> => {
    if (!user.value) return false
    
    try {
      const { data, error: adminError } = await supabase.rpc('is_admin')

      if (adminError) {
        console.error('Error checking admin status:', adminError)
        return false
      }

      return data as boolean
    } catch (err) {
      console.error('Error in isAdmin:', err)
      return false
    }
  }

  // 检查是否为版主或管理员
  const isModerator = async (): Promise<boolean> => {
    if (!user.value) return false
    
    try {
      const { data, error: modError } = await supabase.rpc('is_moderator')

      if (modError) {
        console.error('Error checking moderator status:', modError)
        return false
      }

      return data as boolean
    } catch (err) {
      console.error('Error in isModerator:', err)
      return false
    }
  }

  // 获取当前用户
  const getCurrentUser = async () => {
    try {
      console.log('获取当前用户...')
      const { data: { user: currentUser }, error } = await supabase.auth.getUser()
      
      if (error) {
        console.error('获取当前用户时出错:', error)
        user.value = null
      } else {
        console.log('当前用户:', currentUser?.email || '未登录')
        user.value = currentUser
        if (currentUser) {
          await fetchUserProfile(currentUser.id)
          await checkUserRole()
        }
      }
    } catch (error) {
      console.error('获取当前用户时发生异常:', error)
      user.value = null
    } finally {
      loading.value = false
    }
  }

  // 获取用户资料
  const fetchUserProfile = async (userId: string) => {
    if (!userId) return null
    
    profileLoading.value = true
    try {
      const { data: profileData, error } = await supabase
        .from('user_profiles')
        .select('*')
        .eq('user_id', userId)
        .maybeSingle()

      if (error) {
        console.error('Error fetching user profile:', error)
        return null
      }

      if (!profileData) {
        // 自动为当前用户创建资料（如果缺失）
        if (user.value && user.value.id === userId) {
          const defaultName = user.value.email ? user.value.email.split('@')[0] : '用户'
          const { data: created, error: insertError } = await supabase
            .from('user_profiles')
            .insert({
              user_id: userId,
              name: defaultName,
            })
            .select('*')
            .maybeSingle()

          if (insertError) {
            console.error('Error creating missing user profile:', insertError)
            return null
          }

          if (!created) return null

          const createdProfile: User = {
            id: created.user_id,
            name: created.name,
            avatar: created.avatar_url,
            bio: created.bio,
            isAi: created.is_ai,
            followers: created.followers,
            following: created.following,
            uploads: created.uploads,
            createdAt: created.created_at,
          }
          userProfile.value = createdProfile
          return createdProfile
        }
        return null
      }

      const profile: User = {
        id: profileData.user_id,
        name: profileData.name,
        avatar: profileData.avatar_url,
        bio: profileData.bio,
        isAi: profileData.is_ai,
        followers: profileData.followers,
        following: profileData.following,
        uploads: profileData.uploads,
        createdAt: profileData.created_at
      }
      
      userProfile.value = profile
      return profile
    } catch (error) {
      console.error('Error fetching user profile:', error)
      return null
    } finally {
      profileLoading.value = false
    }
  }

  // 更新用户资料
  const updateUserProfile = async (updates: Partial<User>) => {
    if (!userProfile.value || !user.value) return false
    
    try {
      const { error } = await supabase
        .from('user_profiles')
        .update({
          name: updates.name,
          bio: updates.bio,
          avatar_url: updates.avatar,
          updated_at: new Date().toISOString()
        })
        .eq('user_id', user.value.id)
        .select()
        .maybeSingle()

      if (error) throw error

      // 更新本地状态
      userProfile.value = { ...userProfile.value, ...updates }
      return true
    } catch (error) {
      console.error('Error updating user profile:', error)
      return false
    }
  }

  // ==================== 管理员功能 ====================

  // 获取所有用户及其角色
  const getAllUsersWithRoles = async (): Promise<UserWithRole[]> => {
    adminLoading.value = true
    adminError.value = null

    try {
      // 首先检查权限
      const adminStatus = await isAdmin()
      if (!adminStatus) {
        adminError.value = '权限不足：只有管理员可以查看所有用户'
        return []
      }

      const { data, error: fetchError } = await supabase.rpc('get_all_users_with_roles')

      if (fetchError) {
        adminError.value = '获取用户列表失败'
        return []
      }

      return (
        data?.map((item: any) => ({
          id: item.user_id,
          name: item.name,
          avatar: item.avatar_url,
          bio: item.bio,
          isAi: item.is_ai,
          followers: item.followers,
          uploads: item.uploads,
          role: item.role,
        })) || []
      )
    } catch (err) {
      console.error('Error in getAllUsersWithRoles:', err)
      adminError.value = '获取用户列表失败'
      return []
    } finally {
      adminLoading.value = false
    }
  }

  // 设置用户角色
  const setUserRole = async (params: SetUserRoleParams): Promise<SetUserRoleResponse> => {
    try {
      const { data, error: setError } = await supabase.rpc('set_user_role', params)

      if (setError) {
        return {
          success: false,
          error: setError.message,
        }
      }

      return data as SetUserRoleResponse
    } catch (err) {
      console.error('Error in setUserRole:', err)
      return {
        success: false,
        error: '设置用户角色失败',
      }
    }
  }

  // 批量设置用户角色
  const batchSetUserRoles = async (
    params: BatchSetUserRolesParams,
  ): Promise<BatchSetUserRolesResponse> => {
    try {
      const { data, error: batchError } = await supabase.rpc('batch_set_user_roles', params)

      if (batchError) {
        return {
          success: false,
          error: batchError.message,
          results: [],
          summary: { total: 0, success: 0, error: 0 }
        }
      }

      return data as BatchSetUserRolesResponse
    } catch (err) {
      console.error('Error in batchSetUserRoles:', err)
      return {
        success: false,
        error: '批量设置用户角色失败',
        results: [],
        summary: { total: 0, success: 0, error: 0 }
      }
    }
  }

  // 获取角色变更日志
  const getRoleChangeLogs = async (limit: number = 50): Promise<RoleChangeLog[]> => {
    try {
      const { data, error: logsError } = await supabase
        .from('role_change_logs')
        .select('*')
        .order('changed_at', { ascending: false })
        .limit(limit)

      if (logsError) {
        console.error('Error fetching role change logs:', logsError)
        return []
      }

      return data || []
    } catch (err) {
      console.error('Error in getRoleChangeLogs:', err)
      return []
    }
  }

  // 获取管理员统计信息
  const getAdminStats = async (): Promise<AdminStats | null> => {
    adminLoading.value = true
    adminError.value = null

    try {
      // 获取用户统计
      const { count: totalUsers } = await supabase
        .from('user_profiles')
        .select('*', { count: 'exact', head: true })

      // 获取电影统计
      const { count: totalMovies } = await supabase
        .from('movies')
        .select('*', { count: 'exact', head: true })

      // 获取评论统计
      const { count: totalComments } = await supabase
        .from('comments')
        .select('*', { count: 'exact', head: true })

      // 获取角色分布
      const { data: roleStats } = await supabase.from('user_roles').select('role')

      const usersByRole = {
        user: 0,
        moderator: 0,
        admin: 0,
      }

      roleStats?.forEach((item: any) => {
        if (item.role in usersByRole) {
          usersByRole[item.role as keyof typeof usersByRole]++
        }
      })

      // 获取最近活动（最近7天）
      const sevenDaysAgo = new Date()
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)

      const { count: newUsers } = await supabase
        .from('user_profiles')
        .select('*', { count: 'exact', head: true })
        .gte('created_at', sevenDaysAgo.toISOString())

      const { count: newMovies } = await supabase
        .from('movies')
        .select('*', { count: 'exact', head: true })
        .gte('created_at', sevenDaysAgo.toISOString())

      const { count: newComments } = await supabase
        .from('comments')
        .select('*', { count: 'exact', head: true })
        .gte('created_at', sevenDaysAgo.toISOString())

      return {
        total_users: totalUsers || 0,
        total_movies: totalMovies || 0,
        total_comments: totalComments || 0,
        users_by_role: usersByRole,
        recent_activity: {
          new_users: newUsers || 0,
          new_movies: newMovies || 0,
          new_comments: newComments || 0,
        },
      }
    } catch (err) {
      console.error('Error in getAdminStats:', err)
      adminError.value = '获取统计信息失败'
      return null
    } finally {
      adminLoading.value = false
    }
  }

  // 初始化认证监听器
  const initAuthListener = async () => {
    console.log('初始化认证监听器...')
    
    // 先获取当前用户，等待完成
    await getCurrentUser()
    
    // 监听认证状态变化
    if (authSubscription) {
      return
    }

    const { data: { subscription } } = supabase.auth.onAuthStateChange(async (event, session) => {
      console.log('认证状态变化:', event, session?.user?.email)
      
      user.value = session?.user ?? null
      loading.value = false
      
      if (session?.user) {
        await fetchUserProfile(session.user.id)
        await checkUserRole()
        // 登录后初始化消息系统（单例，幂等）
        try {
          const { useMessages } = await import('../composables/useMessages')
          await useMessages().init()
        } catch (e) {
          console.error('初始化消息系统失败:', e)
        }
        // 登录成功后关闭模态框
        showLoginModal.value = false
        showRegisterModal.value = false
      } else {
        userProfile.value = null
        currentUserRole.value = 'user'
        // 登出后清理消息状态与订阅
        try {
          const { useMessages } = await import('../composables/useMessages')
          useMessages().clearMessages()
        } catch (e) {
          console.error('清理消息系统失败:', e)
        }
      }
    })

    authSubscription = subscription
  }

  // 释放认证监听器
  const disposeAuthListener = () => {
    try {
      authSubscription?.unsubscribe?.()
    } finally {
      authSubscription = null
    }
  }

  // 模态框控制方法
  const openLoginModal = () => {
    showLoginModal.value = true
    showRegisterModal.value = false
  }

  const openRegisterModal = () => {
    showRegisterModal.value = true
    showLoginModal.value = false
  }

  const closeLoginModal = () => {
    showLoginModal.value = false
  }

  const closeRegisterModal = () => {
    showRegisterModal.value = false
  }

  const closeAllModals = () => {
    showLoginModal.value = false
    showRegisterModal.value = false
  }

  // 计算属性
  const isAuthenticated = computed(() => !!user.value)
  const userId = computed(() => user.value?.id)
  const currentUser = computed(() => userProfile.value)
  const isCurrentUser = computed(() => (id: string) => userProfile.value?.id === id)
  const userInitials = computed(() => {
    if (userProfile.value?.name) {
      return userProfile.value.name[0]?.toUpperCase() || 'U'
    }
    if (user.value?.email) {
      return user.value.email[0]?.toUpperCase() || 'U'
    }
    return 'U'
  })
  
  // 权限计算属性
  const canManageUsers = computed(() => currentUserRole.value === 'admin')
  const canModerateContent = computed(() => ['moderator', 'admin'].includes(currentUserRole.value))
  const canViewAdminPanel = computed(() => ['moderator', 'admin'].includes(currentUserRole.value))

  return {
    // 状态
    user,
    userProfile,
    loading,
    profileLoading,
    currentUserRole,
    roleLoading,
    adminLoading,
    adminError,
    showLoginModal,
    showRegisterModal,
    
    // 计算属性
    isAuthenticated,
    userId,
    currentUser,
    isCurrentUser,
    userInitials,
    canManageUsers,
    canModerateContent,
    canViewAdminPanel,
    
    // 认证方法
    signUp,
    signIn,
    signOut,
    signInWithGoogle,
    resendConfirmationEmail,
    resetPassword,
    getCurrentUser,
    initAuthListener,
    
    // 权限检查方法
    checkUserRole,
    isAdmin,
    isModerator,
    
    // 模态框控制方法
    openLoginModal,
    openRegisterModal,
    closeLoginModal,
    closeRegisterModal,
    closeAllModals,
    
    // 用户资料方法
    fetchUserProfile,
    updateUserProfile,
    
    // 管理员功能方法
    getAllUsersWithRoles,
    setUserRole,
    batchSetUserRoles,
    getRoleChangeLogs,
    getAdminStats,
    disposeAuthListener,
  }
})
